<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
 */

namespace App\Library\Cache;


use Hyperf\Redis\RedisFactory;
use Psr\Container\ContainerInterface;

class CacheService
{

    private $handlerMaster; // 主
    private $handlerSlave;  // 从

    public function __construct(ContainerInterface $container)
    {

        $this->handlerMaster = $container->get(RedisFactory::class)->get('default');

        $this->handlerSlave = $container->get(RedisFactory::class)->get('slave');

    }

    public function __call($method, $args)
    {
        $handler = $this->handlerSlave;

        $array = ['set','del','expire','expireat','expireat','persist','getset','setbit','setex','setnx','setrange','mset','msetnx','psetex','incr','incrby','incrbyfloat','decr','decrby','append','append','hdel','hincrby','hincrbyfloat','hmset','hset','hsetnx','blpop','brpop','brpoplpush','linsert','lpop','lpush','lpushx','lrem','lset','ltrim','rpop','rpoplpush','rpush','rpushx','sadd','sdiffstore','sinterstore','smove','spop','srem','sunionstore','zadd','zincrby','zinterstore','zrem','zremrangebylex','zremrangebyrank','zremrangebyscore','zunionstore','pfadd','pfmerge','psubscribe','pubsub','publish','punsubscribe','subscribe','unsubscribe','discard','exec','multi','unwatch','watch', 'pipeline'];
        $method = strtolower($method);

        if (in_array($method, $array)) {
            $handler = $this->handlerMaster;
        }

        return call_user_func_array([$handler, $method], $args);
    }

    public function lock($key, $value=1, $timeout=10)
    {
        return $this->handlerMaster->set($key, $value, ['EX'=>$timeout, 'NX']);
    }

    public function getLock($key)
    {
        return $this->handlerMaster->get($key);
    }


    public function unLock($key)
    {
        return $this->handlerMaster->del($key);
    }


}